package com.alex.common.tools;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import org.apache.commons.lang.StringUtils;

public abstract class ChineseUtils {
	private static final HanyuPinyinOutputFormat FORMAT;

	static {
		FORMAT = new HanyuPinyinOutputFormat();
		FORMAT.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		// format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		FORMAT.setVCharType(HanyuPinyinVCharType.WITH_V);
	}

	// http://www.aqee.net/increase-your-mind-strength-learn-a-new-language-platform/
	// = 60
	public static String toHanyuPinyinString(String cStr, int lengthLimit)
			throws BadHanyuPinyinOutputFormatCombination {
		if (StringUtils.isEmpty(cStr))
			return cStr;

		char[] cStrc = cStr.trim().toCharArray();
		StringBuilder strB = new StringBuilder(cStrc.length * 3);
		for (char c : cStrc) {
			if (c == ' ') {
				strB.append('_');
			} else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
					|| (c >= '0' && c <= '9') || c == '-' || c == '_') {
				strB.append(c);
			} else {
				String[] pinyinStr = PinyinHelper.toHanyuPinyinStringArray(c,
						FORMAT);
				if (pinyinStr != null) {
					strB.append(pinyinStr[0]);
				}
			}
			if (strB.length() >= lengthLimit) {
				break;
			}
		}

		return strB.toString();
	}
}
